var express = require('express');

const common = require('../../libs/common');
const mysql = require('mysql');

var db = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'mysql123456',
    database: '180618'
});

module.exports = function(){
    var router = express.Router();

    //登录网页打开
    router.get('/',(req,res)=>{
        res.render('admin/login.ejs',{});
    });

    //登录请求
    router.post('/',(req, res)=>{
        //console.log(req.body);
        var username = req.body.username;
        var password = common.md5(req.body.password+common.MD5_SUFFIX);

        db.query(`select * from admin_table where username='${username}'`,(err,data)=>{
            if(err){
                console.log(err);
                res.status(500).send('database error').end();
            }else{
                if(data.length == 0){
                    res.status(400).send('no this admin').end();
                }else{
                    if(data[0].password == password){
                        console.log('登录成功');
                        req.session['admin_id'] = data[0].ID;
                        res.redirect('/admin/');
                    }else{
                        res.status(400).send('this password is incorrect').end();
                    }
                }
            }
        });

        //res.render('admin/login.ejs',{});
    });

    return router;
};